package LeetCode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}16:01
 */
public class LeetCode144 {

    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
    }

//    public List<Integer> preorderTraversal(TreeNode root) {//递归处理
//        List<Integer> list = new ArrayList<>();
//        preorder(root,list);
//        return list;
//    }
//    public void preorder(TreeNode root,List<Integer> list){
//        if (root==null){
//            return;
//        }else {
//            list.add(root.val);
//            preorder(root.left,list);
//            preorder(root.right,list);
//        }
//    }
public List<Integer> preorderTraversal(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    LinkedList<Integer> output = new LinkedList<>();
    if (root == null) {
        return output;
    }

    stack.add(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pollLast();
        output.add(node.val);
        if (node.right != null) {
            stack.add(node.right);
        }
        if (node.left != null) {
            stack.add(node.left);
        }
    }
    return output;
}

}
